package com.demo.common.ratelimit.config;

import com.demo.common.ratelimit.annotation.EnableFxwLimiter;
import com.demo.common.ratelimit.interceptor.UserApiInterceptor;
import com.demo.common.ratelimit.interceptor.UserWebInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Collections;
import java.util.List;

/**
 * @Author：DayDayUp
 * @Create：2023/4/7 15:51
 */
@Import(BeanInitConfig.class)
@ConditionalOnBean(annotation = EnableFxwLimiter.class)
@EnableConfigurationProperties(RateLimiterProperties.class)
public class RateLimiterAutoConfiguration implements WebMvcConfigurer {

    @Autowired(required = false)
    private RateLimiterProperties rateLimiterProperties;

    @Autowired(required = false)
    private UserApiInterceptor userApiInterceptor;

    @Autowired(required = false)
    private UserWebInterceptor userWebInterceptor;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludeUrlList;
        if (rateLimiterProperties.getExcludeUrlList() != null) {
            excludeUrlList = rateLimiterProperties.getExcludeUrlList();
        }else {
            excludeUrlList = Collections.emptyList();
        }
        if (userApiInterceptor != null) {
            registry.addInterceptor(userApiInterceptor).addPathPatterns("/**")
                    .excludePathPatterns(excludeUrlList);
        }
        if (userWebInterceptor != null) {
            registry.addInterceptor(userWebInterceptor).addPathPatterns("/**")
                    .excludePathPatterns(excludeUrlList);
        }
    }
}
